//
//  MainViewController.m
//  二级评论
//
//  Created by Andrew on 2018/1/19.
//  Copyright © 2018年 Andrew. All rights reserved.
//

#import "MainViewController.h"
#import "MainTableViewCell.h"
#import "FamilyGroup.h"
#import "FamilyGroupFrame.h"
#import "YMInputTextView.h"

@interface MainViewController () <UITableViewDelegate,UITableViewDataSource>
{
    int keyBoardH;
}

/* tableView */
@property (nonatomic, weak) UITableView *tableView;
/* 数据 */
@property (nonatomic, strong) NSMutableArray *datasource;
/* 蒙层 */
@property (nonatomic, weak) UIView *coverView;
/* 输入框 */
@property (nonatomic, weak) YMInputTextView *inputView;



@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    
    [self setupData];
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//创建数据
- (void)setupData
{
    NSString *fullPath = [[NSBundle mainBundle] pathForResource:@"FamilyGroup.plist" ofType:nil];
    NSArray *dictArray = [NSArray arrayWithContentsOfFile:fullPath];
    NSMutableArray *models = [NSMutableArray arrayWithCapacity:[dictArray count]];
    for (NSDictionary *dict in dictArray) {
        FamilyGroup *fmailyGroup = [FamilyGroup familyGroupWithDict:dict];
        FamilyGroupFrame *frame = [[FamilyGroupFrame alloc] init];
        frame.model = fmailyGroup;
        [models addObject:frame];
        
    }
    [self.datasource addObjectsFromArray:models];
    [self.tableView reloadData];
    
}

//创建tableView
- (void)setupTableView
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0,SCREENWIDTH, SCREENHEIGHT)];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    self.tableView = tableView;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datasource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FamilyGroupFrame *frame = self.datasource[indexPath.row];
    return frame.cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    MainTableViewCell *cell = [MainTableViewCell cellWithTableVie:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.indexPath = indexPath;
    cell.frameModel = self.datasource[indexPath.row];
    //评论
    __weak typeof(self) weakSelf = self;
    cell.commentBringParamBlock = ^(NSIndexPath *indexPath) {
        [weakSelf commentClick:indexPath friendName:@""];
    };
    //回复
    cell.commentReplayBlock = ^(NSIndexPath *indexPath, NSString *friendName) {
        [weakSelf commentClick:indexPath friendName:friendName];
    };
    
    return cell;
}

- (void)commentClick:(NSIndexPath *)indexPath friendName:(NSString *)friendName
{
    /* 蒙层 */
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT)];
    coverView.backgroundColor = [UIColor clearColor];
    [window addSubview:coverView];
    self.coverView = coverView;
    
    //给蒙层添加手势
    UITapGestureRecognizer *coverTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(coverTap)];
    [self.coverView addGestureRecognizer:coverTap];
    
    //添加输入框
    YMInputTextView *inputView = [[YMInputTextView alloc] initWithFrame:CGRectMake(0, SCREENHEIGHT, SCREENWIDTH, 60)];
    inputView.indexPath = indexPath;
    [self.coverView addSubview:inputView];
    self.inputView = inputView;
    
    __weak typeof(self) WeakSelf = self;
    [UIView animateWithDuration:0.35 animations:^{
        WeakSelf.inputView.ym_y = SCREENHEIGHT - keyBoardH - 60;
    }];
    
    //回传
    self.inputView.InputTextViewReturnBlock = ^(NSIndexPath *indexPath, NSString *commentText) {
        [WeakSelf inputComment:indexPath commentText:commentText friendName:friendName];
    };
}

//点击蒙层退出键盘
- (void)coverTap
{
    //退出键盘
    [self.coverView removeFromSuperview];
    __weak typeof(self) WeakSelf = self;
    [UIView animateWithDuration:0.35 animations:^{
        WeakSelf.coverView.ym_y = SCREENHEIGHT;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WeakSelf.coverView removeFromSuperview];
        });
    }];
}

//评论
- (void)inputComment:(NSIndexPath *)indexPath commentText:(NSString *)commentText friendName:(NSString *)friendName
{
    //退出键盘
    [self coverTap];
    
    NSMutableArray *replayS = [NSMutableArray new];
    FamilyGroupFrame *frame = self.datasource[indexPath.row];
    
    if (frame.model.replys.count) {
        [replayS addObjectsFromArray:frame.model.replys];
    }
    //用户的名字
    NSString *name = @"余默";
    NSString *comment = @"";
    if (friendName.length) { //回复
        NSString *nameText = [NSString stringWithFormat:@"%@回复%@",name,friendName];
        comment = [NSString stringWithFormat:@"%@：%@",nameText,commentText];
    } else {
        comment = [NSString stringWithFormat:@"%@：%@",name,commentText];
    }
    
    [replayS addObject:comment];
    
    //先取model，赋值
    FamilyGroup *model = [[FamilyGroup alloc] init];
    model = frame.model;
    model.replys = replayS;
    //赋值之后，在赋值到原来的frameModel
    frame.model = model;
    
    [self.datasource replaceObjectAtIndex:indexPath.row withObject:frame];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyBoardH = keyboardRect.size.height;
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    
}


#pragma mark - 懒加载
- (NSMutableArray *)datasource
{
    if (!_datasource) {
        _datasource = [NSMutableArray new];
    }
    return _datasource;
}


@end
